import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getClientList, clientOffline } from "@/api/monitor";
import { reactive, ref, onMounted, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";

export function useRole() {
  const form = reactive({
    username: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      prop: "id",
      type: "index",
      minWidth: 60
    },
    {
      label: "客户端地址",
      prop: "clientAddr",
      minWidth: 100
    },
    {
      label: "目标地址",
      prop: "targetAddr",
      minWidth: 140
    },
    {
      label: "客户端连接时间",
      prop: "connectTime",
      minWidth: 180,
      formatter: ({ connectTime }) =>
        dayjs(connectTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "发送的字节数",
      prop: "bytesSent",
      minWidth: 100,
      formatter: ({ bytesSent }) => {
        return (bytesSent / 1024).toFixed(2) + "KB";
      }
    },
    {
      label: "接收的字节数",
      prop: "bytesReceived",
      minWidth: 100,
      formatter: ({ bytesReceived }) => {
        return (bytesReceived / 1024).toFixed(2) + "KB";
      }
    },
    {
      label: "客户端状态",
      prop: "status",
      minWidth: 100,
      formatter: ({ status }) => {
        const statusMap = {
          1: "认证阶段",
          2: "请求阶段",
          3: "relay阶段"
        };
        return statusMap[status];
      }
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function handleOffline(row) {
    const result = await clientOffline(row.client_addr);
    if (result.success) {
      message(`${row.client_addr}已被强制下线`, { type: "success" });
      onSearch();
    } else {
      message(result.message, { type: "error" });
    }
  }

  async function onSearch() {
    loading.value = true;
    const result = await getClientList(toRaw(form));
    if (!result) return;
    const { data } = result;
    dataList.value = data;
    // pagination.total = data.total;
    // pagination.pageSize = data.page_size;
    // pagination.currentPage = data.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    handleOffline,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
